#!/bin/bash

set -e

# 可执行文件路径
BINARY=./../bin_dpu/feature_preprocess

# 参数枚举（虽然只有一个值，也保留枚举逻辑）
ELE_NUM_LIST=(1)
FEATURE_NUM_LIST=(1)

# batch_size 枚举（直接使用实际数值）
BATCH_SIZES=(64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 \
             1048576 2097152 4194304 8388608 16777216 33554432 67108864 \
             )

# 设备类型和线程数映射
DEVICE_TYPES=("dpu" "dpa")
declare -A THREADS_HOST_MAP
THREADS_HOST_MAP["dpu"]="1 2 4 8 12 16"
THREADS_HOST_MAP["dpa"]="1 2 4 8 12 16 32 64 96 128 160 192 224 256"

# 操作类型
# ALL_OP_TYPES=("logit" "boxcox" "onehot" "bucketize" "sigrid_hash" "clamp_list" \
#               "ngram" "firstx" "mapid" "fillnull" "cast")

ALL_OP_TYPES=("sigrid_hash" "clamp_list" \
              "ngram" "logit")

# dpa 不支持的操作类型
UNSUPPORTED_OPS_FOR_DPA=("logit" "boxcox" "onehot" "bucketize")

# 输出目录
OUT_DIR="results_raw"
mkdir -p "$OUT_DIR"

# 遍历所有组合
for ele_num in "${ELE_NUM_LIST[@]}"; do
  for feature_num in "${FEATURE_NUM_LIST[@]}"; do
    for device in "${DEVICE_TYPES[@]}"; do
      threads_list=${THREADS_HOST_MAP[$device]}

      # 根据设备类型过滤操作类型
      if [[ "$device" == "dpa" ]]; then
        OP_TYPES=()
        for op in "${ALL_OP_TYPES[@]}"; do
          if [[ ! " ${UNSUPPORTED_OPS_FOR_DPA[@]} " =~ " ${op} " ]]; then
            OP_TYPES+=("$op")
          fi
        done
      else
        OP_TYPES=("${ALL_OP_TYPES[@]}")
      fi

      for op in "${OP_TYPES[@]}"; do
        # 创建 device/op_type 子目录
        OP_OUT_DIR="${OUT_DIR}/${device}/${op}"
        mkdir -p "$OP_OUT_DIR"

        for batch in "${BATCH_SIZES[@]}"; do
          for threads in $threads_list; do
            if (( batch < threads )); then
              echo "Skipping device=$device op=$op batch=$batch threads=$threads (batch < threads)"
              continue
            fi

            echo "Running device=$device op=$op batch=$batch threads=$threads"

            # 构造输出文件名
            FILENAME="output_bs${batch}_fn${feature_num}_en${ele_num}_th${threads}.txt"
            OUTPUT_PATH="${OP_OUT_DIR}/${FILENAME}"

            # 执行命令并提取目标行
            RAW_OUTPUT=$($BINARY \
              --threads_host=$threads \
              --arg_batch_size=$batch \
              --arg_feature_num=$feature_num \
              --arg_ele_num=$ele_num \
              --device_type=$device \
              --op_type=$op)

            # 提取目标 op_type 的一行
            TARGET_LINE=$(echo "$RAW_OUTPUT" | grep -i -E "^\|[[:space:]]*${op}[[:space:]]*\|")

            if [[ -z "$TARGET_LINE" ]]; then
              echo "Warning: No line found for op_type=$op in output"
              echo "$RAW_OUTPUT" > "${OUTPUT_PATH}.full"  # 保存完整输出用于排查
              continue
            fi

            # 保存目标行
            echo "$TARGET_LINE" > "$OUTPUT_PATH"
            echo "Saved: $OUTPUT_PATH"

            sleep 1
          done
        done
      done
    done
  done
done
